import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';

import 'page_list_control.dart';

typedef ItemBuilder<T> = Widget Function(BuildContext context, int index, T data);

/// 继承该类的Widget就有了上拉加载下拉刷新的功能
class PageListWidget<T, C extends PageListControl<T>> extends StatelessWidget {
  final ItemBuilder<T> _createItem;

  final bool _enableRefresh;
  final bool _enableLoad;

  PageListWidget({
    bool enableRefresh: true,
    bool enableLoad: true,
    required ItemBuilder<T> createItem,
  })   : this._createItem = createItem,
        this._enableRefresh = enableRefresh,
        this._enableLoad = enableLoad;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<C>(
      builder: (PageListControl control) {
        return EasyRefresh.custom(
          taskIndependence: true,
          enableControlFinishRefresh: true,
          enableControlFinishLoad: true,
          firstRefresh: true,
          controller: control.easyRefreshController,
          scrollController: control.scrollController,
          onRefresh: _enableRefresh ? control.onRefresh : null,
          onLoad: _enableLoad ? control.onLoad : null,
          header: ClassicalHeader(
            enableHapticFeedback: true,
            bgColor: Colors.transparent,
            infoColor: Colors.teal,
            refreshText: '下拉刷新',
            refreshReadyText: '释放刷新',
            refreshingText: '刷新中...',
            refreshedText: '刷新成功',
            refreshFailedText: '刷新失败',
            noMoreText: '没有更多数据',
            infoText: '更新于 %T',
          ),
          footer: ClassicalFooter(
            enableHapticFeedback: true,
            noMoreText: '没有了',
            infoText: '更新于 %T',
            loadingText: '加载中...',
            loadedText: '加载完成',
            loadFailedText: '加载失败',
          ),
          slivers: [
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  return _createItem(context, index, control.dataList[index]);
                },
                childCount: control.dataList.length,
              ),
            ),
          ],
        );
      },
    );
  }
}
